# -*- coding: utf-8 -*-
import base64
import hashlib
import hmac
import json

import requests
from datetime import datetime
from django.conf import settings

from common.utils import exceptions as err
from common.utils import track_logging
from common.withdraw.model import WITHDRAW_ORDER_STATUS

_LOGGER = track_logging.getLogger('withdraw')

# 同略云API使用香港代理访问
# _GATEWAY = 'https://www.tly-transfer.com/sfisapi/'
_GATEWAY = settings.THIRD_URL + 'sfisapi/'

APP_CONF = {
    'itech': {
        'NAME': 'itech_withdraw',
        'API_KEY': '6790ae3cb0ccdecebd64f5d21f3df064b4dbb934e38a75f163bbe986'
    }
}


def _get_api_key(app_name):
    return APP_CONF[app_name]['API_KEY']


def _generate_sign(data, key):
    sign = hmac.new(key, msg=data, digestmod=hashlib.sha256).digest()
    return base64.b64encode(sign).decode()


def create_order(order, channel):
    app_name = 'itech'
    auto_flag = channel.appid
    app_key = _get_api_key(app_name)
    data = {
        'module': 'order',
        'method': 'api_add_order',
        'company_name': 'ITECH',
    }
    payload = {
        'card_number': order.pay_account_num,
        'amount': order.amount,
        'trans_mode': 'out_trans',
        'order_number': str(order.id),
        'atfs_flag': auto_flag,
        'real_name': order.pay_account_username,
    }
    data['payload'] = payload
    sign = _generate_sign(json.dumps(data), app_key)
    headers = {
        'TLYHMAC': sign,
        'Content-type': 'application/json',
        'Accept': 'text/plain'
    }

    # 先设置为三方未知状态
    order.status = WITHDRAW_ORDER_STATUS.THIRD_UNKNOWN
    order.third_type = channel.id
    order.save()

    response = requests.post(_GATEWAY, headers=headers, data=json.dumps(data), timeout=5)
    _LOGGER.info('tonglue withdraw reply: %s' % response.content)
    json_data = json.loads(response.content)
    success = json_data.get('success', None)
    third_id = json_data.get('data', {}).get('order_id', None)
    if success and third_id:
        order.status = WITHDRAW_ORDER_STATUS.THIRD
        order.third_id = str(third_id)
        order.extra_info = response.content
        order.save()
        return True
    else:
        order.detail = json_data.get('message', '')
        order.status = WITHDRAW_ORDER_STATUS.THIRD_FAIL
        order.extra_info = response.content
        order.save()
        return False


def _verify_notify_sign(data, sign, app_name):
    app_key = _get_api_key(app_name)
    calculated_sign = _generate_sign(data, app_key)
    if sign != calculated_sign:
        _LOGGER.info("tonglue withdraw sign: %s, calculated sign: %s", sign, calculated_sign)
        raise err.ParamError('tonglue sign not pass, data: %s' % data)


def check_bankcard_withdraw_notify(data, sign, order):
    ''' 同略云回调 '''
    app_name = 'itech'
    _verify_notify_sign(data, sign, app_name)
    json_data = json.loads(data)
    order_id = json_data['order_number']
    trade_status = json_data['status']
    if trade_status == 'SUCCESS':
        _LOGGER.info('tonglue withdraw success: %s' % data)
        order.status = WITHDRAW_ORDER_STATUS.DONE
        order.extra_info = data
        order.third_notify_at = datetime.utcnow()

        order.save()
        return True
    elif trade_status == 'FAIL':
        _LOGGER.info('tonglue withdraw fail: %s' % data)
        order.status = WITHDRAW_ORDER_STATUS.THIRD_FAIL
        order.extra_info = data
        order.third_notify_at = datetime.utcnow()

        order.save()
        return False
    else:
        raise err.ParamError('status invalid')


if __name__ == "__main__":
    print create_order()
